from django.shortcuts import render

# Create your views here.
from django.http import HttpResponse
import requests
import time
from bs4 import BeautifulSoup
import re
import json
import urllib

#返回结果格式
def resultData():
    data = {
        "websiteType" : 0,
        "titleName":"",
        "titleHref": "",
        "source":"",
        "label":"",
        "volume":"",
        "summary":"",
        "detailId":'',
        "publishTime" :"",
        "category" : "",
        "quote" :"",
        "abstract": "",
        "doi": "",
        "downLoad": "",
        "keyword": [],
        "author": [],

    }
    return data

def formData(response):


    allData = []

    lis = response.json()["results"]["result"]["doc"]

    i = 1

    for li in lis:
        tempData = resultData()

        try:
            tempData["titleName"] = li["GivenDocumentTitle"]
        except:
            pass
        try:
            tempData["titleHref"] = "https://psycnet.apa.org/search/display?id={}&recordId={}&tab=PA&page=1&display=25&sort=PublicationYearMSSort%20desc,AuthorSort%20asc&sr=1".format(response.json()["search"]["id"],i)
        except:
            pass

        try:
            tempData["author"] = li["AuthorName"]
        except:
            pass

        try:
            tempData["doi"] = li["DOI"]
        except:
            pass

        try:
            tempData["publishTime"] = li["PublicationDate"]
        except:
            pass

        try:
            tempData["source"] = li["SourcePI"]
        except:
            pass

        i += 1

        allData.append(tempData)

    return allData

def getData(keyword):

    headers = {
        'Origin': 'https://psycnet.apa.org',
        'Accept-Encoding': 'gzip, deflate, br',
        'Accept-Language': 'zh-CN,zh;q=0.9,en;q=0.8',
        'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.96 Safari/537.36',
        'Content-Type': 'application/json',
        'Accept': 'application/json, text/plain, */*',
        'Referer': 'https://psycnet.apa.org/search/results?id=37758447-b337-f4c0-1e35-1bf1ae40e3e7',
        'X-Requested-With': 'XMLHttpRequest',
        'Connection': 'keep-alive',
        'X-Distil-Ajax': 'dxrucdxavtqfexaattatqysrrecxyyy',
    }

    data = '{"api":"search.results","params":{"id":"37758447-b337-f4c0-1e35-1bf1ae40e3e7","type":"search","productFilter":"","friendlyQuery":"<span class=\\"fq-field\\">Any Field</span>: <span class=\\"fq-value\\">cell</span>","totalRecords":"1498","metadata":{"uid":"","excludeFromLogs":false,"hasBeenLogged":true,"auto":true,"fromDoi":false,"directUID":false,"bypassML":false},"query":{"criteria":[{"field":"AnyField","operator":"OR","value":"' + keyword +'","source":"user"}],"limits":[],"filter":{"onlyShow":{"ftOnly":false,"impactStatement":false,"latestUpdate":false,"openAccess":false,"peerReviewed":false,"testAvailable":false},"dateRange":{"begin":"eternity","end":"eternity","field":"PublicationYear","puby1":"*","yearRange":"All years"},"facets":[]},"displayOptions":{"pageSize":25,"sort":[{"field":"PublicationYearMSSort","direction":"desc"},{"field":"AuthorSort","direction":"asc"}]},"nativeOptions":{"pb":{"type":{"conferenceProceedings":false,"handbookManual":false,"referenceBook":false,"classicBook":false,"textbookStudyGuide":false},"publicationType":{"authored":false,"edited":false},"audience":{"generalPublic":false,"professional":false}}},"databases":["PI","PA","PB","PE"],"tab":"all","source":"advanced","viewMode":"psycnet","index":"psycnet"},"responseParameters":{"start":0,"rows":25,"facet":false,"results":true,"hl":true,"fl":"UID","fc":"","format":"json"},"timeCreated":"2019-02-12T02:24:33.383Z","queryParameters":{"q":"(AnyField:(cell))","fq":"","boosting":false,"productFilter":"(ProductNameFacet:PsycARTICLES)","sort":"PublicationYearMSSort desc,AuthorSort asc"}}}'

    proxies = {
        "http": "http://qf:qf3.1415@202.112.118.7:10086/"
    }

    response = requests.post('https://psycnet.apa.org/api/request/search.results', headers=headers,
                             data=data,proxies=proxies)

    allData = formData(response)


    return allData


def index(request):

    data = json.loads(request.POST.get('data', '1'))

    allData = getData(data["values"][0])

    return HttpResponse(json.dumps({
        "collection": allData,
        "allNum": 0
    }), content_type="application/json")